<?php

namespace App\Kuafu\Export\Service\ExportFactory;

use App\Kuafu\Export\Model\ExportDownloadModel;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\Statistics\Service\StatisticsService;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use Illuminate\Support\Str;

/**
 * app-外卖订单明细
 */
class ExportAppWmOrderService extends BaseExportService
{
    private string $localPath;

    public function query(): self
    {
        $shopId  = (int)($this->params['shopId'] ?? 0);
        $startAt = $this->params['showStartAt'] ?? time();
        $endAt   = $this->params['showEndAt'] ?? time();

        $content = WaiMaiOrderModel::suffix($shopId)
                                   ->with('shopRel')
                                   ->where('shopId', $shopId)
                                   ->where('orderStatus', '!=', WaiMaiDBEnum::ORDER_STATUS_7)
                                   ->whereBetween('createdAt', [$startAt, $endAt])
                                   ->get()
                                   ->map(function ($item) {

                                       $addressPrefix = explode('-', $item->shopRel->addressPrefix);
                                       unset($addressPrefix[2]);
                                       $addressPrefix = implode('-', $addressPrefix);

                                       $partRefund = $totalRefund = '否';
                                       if ($item->refundPrice > 0) {

                                           if ($item->refundPrice < $item->payPrice) {
                                               $partRefund = '是';
                                           } else {
                                               $totalRefund = '是';
                                           }
                                       }

                                       $redDetails = collect(json_decode($item->redLists, true))->map(function ($item) {
                                           return $item['n'];
                                       })->implode('/');

                                       return [
                                           'date'                  => date('Y-m-d', $item->createdAt->timestamp),
                                           'orderId'               => $item->orderId,
                                           'addressPrefix'         => $addressPrefix,
                                           'shopName'              => $item->shopRel->name,
                                           'shopCode'              => $item->shopRel->shopCode,
                                           'createdAt'             => date('Y-m-d H:i:s', $item->createdAt->timestamp),
                                           'completeTime'          => $item->completeTime ? date('Y-m-d H:i:s',
                                               $item->completeTime) : '',
                                           'orderStatusText'       => WaiMaiDBEnum::ORDER_STATUS_TEXT[$item->orderStatus] ?? '',
                                           'redDetails'            => $redDetails,
                                           'partRefund'            => $partRefund,
                                           'totalRefund'           => $totalRefund,
                                           'payPrice'              => bcdiv100($item->payPrice),
                                           'relPrice'              => bcdiv100($item->originalPrice - $item->originalShippingPrice),
                                           'originalShippingPrice' => bcdiv100($item->originalShippingPrice),
                                           'packingPrice'          => bcdiv100($item->packingPrice),
                                           'redPrice'              => bcdiv100($item->redPrice),
                                           'activityExpenditure'   => bcdiv100($item->activityExpenditure),
                                           'expectIncome'          => bcdiv100($item->expectIncome),
                                       ];
                                   })->toArray();

        $this->localPath = sys_get_temp_dir() . '/' . Str::random();
        self::streamExport($content, $shopId, $startAt, $endAt, $this->localPath);


        return $this;
    }

    public function path(): string
    {
        return $this->upload($this->localPath);
    }


    public static function streamExport(
        array $dataArr,
        int $shopId,
        string $startAt,
        string $endAt,
        string $path
    ): array {

        $shopInfo = ShopService::getShopInfo($shopId);

        $data = self::getToChange($dataArr, $shopInfo);

        // 生成excel
        $fileType = ExportDownloadModel::FILE_TYPE_APP_WM_ORDER;
        $client   = ExportDownloadModel::CLIENT_TYPE_APP;
        $fileName = (new ExportDownloadModel())->buildFileName($shopId, strtotime($startAt), strtotime($endAt),
            $fileType, $client);

        StatisticsService::spreadsheetExcel([
            [
                'info'  => $data['info'],
                'title' => $data['title'],
                'rows'  => iterator_to_array($data['rows']),// 把yield转成数组
            ]
        ], $fileName, $path);

        return $data;
    }

    /**
     * 导出信息组装
     * @param $storeOrderList
     * @param $shopInfo
     * @return array
     */
    public static function getToChange(
        $storeOrderList,
        $shopInfo
    ): array {
        $rows = self::yieldOrderInfo($storeOrderList);
        return [
            'title' => '外卖订单明细',
            'info'  => [
                '门店'   => $shopInfo['name'],
                '门店编码' => str_pad($shopInfo['shopCode'],
                    ShopCodeEnum::CODE_TEXT[ShopCodeEnum::LEADING_ZERO], "0", STR_PAD_LEFT),//门店编号
            ],
            'rows'  => $rows
        ];
    }

    public static function yieldOrderInfo($orderList): \Generator
    {
        $rows = [
            '日期',
            '订单编号',
            '门店所在城市',
            '门店名称',
            '门店id',
            '下单时间',
            '完成时间',
            '订单状态',
            '活动信息',
            '是否部分退款',
            '是否全额退款',
            '顾客实付',
            '商品原价',
            '配送费',
            '包装费',
            '活动补贴(平台+商家)',
            '商家活动支出',
            '营业收入',
        ];
        yield $rows;
        foreach ($orderList as $key => $value) {
            $rows[$key + 1] = [
                $value['date'],
                $value['orderId'] . ' ',
                $value['addressPrefix'],
                $value['shopName'],
                $value['shopCode'],
                $value['createdAt'],
                $value['completeTime'],
                $value['orderStatusText'],
                $value['redDetails'],
                $value['partRefund'],
                $value['totalRefund'],
                $value['payPrice'],
                $value['relPrice'],
                $value['originalShippingPrice'],
                $value['packingPrice'],
                $value['redPrice'],
                $value['activityExpenditure'],
                $value['expectIncome'],
            ];
            yield $rows[$key + 1];
        }
    }
}
